package com.guoli.print;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;

import javax.imageio.ImageIO;

public class TestPrintH {
	
	public static void main(String[] args) throws IOException {
		String[] texts = new String[]{"型zyZw","数量"};
		String fontName = "黑体";
		int fontSize = 50;
		String strs[] = getPicString(texts, fontName, fontSize);
		System.out.println(Arrays.toString(strs));
	}
	
	public static String[] getPicString(String[] text, String fontName, int fontSize) throws IOException{
		int width = 0;
		int height = 0;
		int ascent = 0;
		int n=0;
		String[] picString = new String[text.length];
		Font font = new Font(fontName, Font.BOLD, fontSize);
		for(int i=0;i<text.length;i++){
			Graphics g = new BufferedImage(1, 1, 1).getGraphics();
			FontMetrics fm = g.getFontMetrics(font);
			ascent = fm.getAscent();
			width = (int)Math.round(fm.getStringBounds(text[i], g).getWidth());
			width = width%8!=0?(width/8+1)*8:width;
			height = fm.getHeight();
			height = height%8!=0?(height/8+1)*8:height;
			BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D graphics2d = (Graphics2D) bi.getGraphics();
			graphics2d.setColor(Color.WHITE);
			graphics2d.fillRect(0, 0, width, height);
			graphics2d.setColor(Color.BLACK);
			graphics2d.setFont(font);
			graphics2d.drawString(text[i], 0, ascent);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ImageIO.write(bi, "jpg", bos);
			String strx = "";
			String result = "";
			for(int h = 0; h < height; h++){
				for(int w = 0; w < width; w++){
					strx += new Color(bi.getRGB(w, h)).getGreen()==0?"1":"0";
				}
			}
			for(int j = 0;j < strx.length();j++){
				n++;
				if(n % 4 == 0){
					result += Integer.toHexString(Integer.parseInt(strx.substring(j-3,j+1), 2));
					n = 0;
				}
			}
			picString[i] = result.toUpperCase();
			System.out.println(result.toUpperCase());
		}
		return picString;
	}
}
